package cn.hd01.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.hd01.repository.ViewHistoryRepository;
import cn.hd01.repository.entity.ViewHistory;
import cn.hd01.service.ProductService;
import cn.hd01.service.StyleService;
import cn.hd01.service.ViewHistoryService;

@Service
public class ViewHistoryServiceImpl extends BaseServiceImpl<ViewHistory, Integer> implements ViewHistoryService {

	private ViewHistoryRepository repository;

	@Autowired
	private ProductService productService;

	@Autowired
	private StyleService styleService;

	@Autowired
	public ViewHistoryServiceImpl(ViewHistoryRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<ViewHistory> findByUserId(Integer userId, Pageable pageable) {
		Page<ViewHistory> list = repository.findByUserId(userId, pageable);

		for (ViewHistory vh : list.getContent()) {
			if (vh.getType() == ViewHistory.TYPE_PRODUCT) {
				vh.setAttach(productService.findOne(vh.getRefId()));
			}

			if (vh.getType() == ViewHistory.TYPE_STYLE) {
				vh.setAttach(styleService.findOne(vh.getRefId()));
			}
		}

		return list;
	}

	@Override
	public void view(Integer userId, Integer type, Integer refId) {
		ViewHistory vh = repository.findByTypeAndRefId(type, refId);
		if (vh == null) {
			vh = new ViewHistory(type, refId);
			vh.setUserId(userId);
		}
		
		vh.setTimes(vh.getTimes() + 1);
		vh.setUpdateTime(new Date());
		repository.save(vh);
	}
}
